package com.hsnr.familyfinder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class ConnectionHandler {
    private String ip;
    private int port;
    private final String TAG = "FamilyFinder";

    public ConnectionHandler(String ip, int port) {
        this.ip = ip;
        this.port = port;

    }

    public String buildGetString(String name, String group, double lat, double lng, double height, long time,
            String isStart, String action) {
        StringBuilder b = new StringBuilder();
        b.append("http://" + this.ip);
        b.append(":" + port);
        b.append("/family-finder/server/scripts/server.php");
        b.append("?name=" + name);
        b.append("&group=" + group);
        b.append("&lat=" + lat);
        b.append("&long=" + lng);
        b.append("&height=" + height);
        b.append("&time=" + time);
        b.append("&isStart=" + isStart);
        b.append("&action=" + action);
        return b.toString();

    }

    public String sendRequest(String connectionString) {
        MyLog.d(TAG, "Sende GET Request");
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(connectionString);
        HttpResponse response;
        String result = new String();
        try {
            response = client.execute(request);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                line = line.replace("\\n", "\n");
                if (line.equals("")) {
                    continue;
                }
                result += line + System.getProperty("line.separator");
                MyLog.d(TAG, "Antwort: <" + line + ">");

            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public void persistData(String httpOutput) {
        FileTools f = new FileTools();
        f.write("db.csv", httpOutput);
    }

}
